#!/bin/bash
#
# Copyright 2018-2020 IBM Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
set -euo pipefail

export YARN_VERSION=1.22.4

# Download and install Yarn Package Manager
mkdir -p dist
cd dist && wget https://github.com/yarnpkg/yarn/releases/download/v${YARN_VERSION}/yarn-v${YARN_VERSION}.tar.gz
tar -zvxf yarn-v${YARN_VERSION}.tar.gz && rm -rf yarn-v${YARN_VERSION}.tar.gz

# Add to PATH
export PATH=$(pwd)/yarn-v${YARN_VERSION}/bin/:$PATH && cd ..

# Build Elyra Distribution
make release

# Install Elyra Wheel
pip install dist/*.whl

# Rebuild Jupyter Lab to enable extensions
jupyter labextension link --no-build packages/application/
jupyter labextension link --no-build packages/ui-components/
jupyter labextension link --no-build packages/metadata-common/
jupyter lab build --dev-build=False --minimize=False --debug
mkdir -p binder-demo

# Enable debug output
set -x

# Add getting started assets to Docker image
# (1) Clone the examples repository.
git clone https://github.com/elyra-ai/examples.git 

EXAMPLES_BASE_DIR=examples

# (2) Copy all getting started assets to the working directory,
#     which is referenced when binder is invoked, e.g. 
#     https://mybinder.org/v2/gh/elyra-ai/elyra/master?urlpath=lab/tree/binder-demo
cp -r $EXAMPLES_BASE_DIR/binder/getting-started/* binder-demo/

# (3) Remove the code snippets from the working directory.
#     They need to reside in a different location to be usable.
rm -rf binder-demo/code-snippets

# (4) Add code snippet files to the appropriate location
DATA_DIR=`jupyter --data-dir`
CODE_SNIPPETS_DIR="$DATA_DIR/metadata/code-snippets/"
mkdir -p $CODE_SNIPPETS_DIR
cp $EXAMPLES_BASE_DIR/binder/getting-started/code-snippets/*.json $CODE_SNIPPETS_DIR

# (5) Remove cloned examples directory
rm -rf $EXAMPLES_BASE_DIR
